/**
 * 
 */
var rowNumber;
var pageSize;
var pageNumber;
$(function(){
	   $('#role_table').datagrid({
					url : 'admin/queryRoleInfo.do?pageSize=10',
					collapsible : true,
					width : '60%',
					height :'450px',
					iconCls : 'icon-user',
					fitColumns : true,
					fixed:true,
					pagination : true,
					rownumbers : true,
					singleSelect:true,
					checkOnSelect:false,
					selectOnCheck:false,
					loadMsg:'正在加载数据',
					loadFilter:function(data){
							 
						 return data;
					},
					onClickRow: function(rowIndex, rowData) {
						rowNumber=rowIndex;
						
					},
					onDblClickRow :function(rowIndex,rowData){
						//layer.msg("double click");
					  },
					onLoadSuccess:function(data){
							$('#role_table').datagrid('selectRow',rowNumber);
						},
					toolbar:'#toolbar',
					columns : [ [
							{
								field : 'roleName',
								title : '身份类型',
								width : 50,
								align : 'center'
							},
							{
								field : 'roleDescription',
								title : '身份描述',
								width : 50,
								align : 'center'
							}
						   ] ]
				});
	 //设置分页控件  
		var p = $('#role_table').datagrid('getPager');
		$(p).pagination({
			pageSize : 10,//每页显示的记录条数，默认为10  
			pageList : [5,10,20,30,40,50],//可以设置每页记录条数的列表  
			beforePageText : '第',//页数文本框前显示的汉字  
			afterPageText : '页    共 {pages} 页',
			displayMsg : '当前显示 {from} - {to} 条记录   共 {total} 条记录',
			onSelectPage:function(pageNumber, pageSize){ 
				//layer.msg("pageNumber="+pageNumber+"pageSize="+pageSize)
				var datas={
						currentPage : (pageNumber-1)*pageSize,
						pageSize : pageSize
				}
				loadData(datas);
		    },
	 		onRefresh:function(pageNumber, pageSize){
	 			var datas={
						currentPage : (pageNumber-1)*pageSize,
						pageSize : pageSize
				}
				loadData(datas);
	 		}
		}); 
   });
   //toolbar
$(function(){
	$('#create').bind('click',function(){
		$('#rolefm').form('clear');
		$('#roledlg').dialog('open').dialog("setTitle","添加身份");
		$("#saveUrl").val("admin/addRoleInfo.do");
	});
	$('#update').bind('click',function(){
		var row = $('#role_table').datagrid('getSelected');
		if(row){
			$('#rolefm').form('clear');
			$('#roledlg').dialog('open').dialog("setTitle","修改身份");
			$('#rolefm').form('load',row);
			$("#saveUrl").val("admin/updateRoleInfo.do?roleId="+row.roleId);
		}else{
			layer.msg('请选中一行');
		}
	});
	$('#distribution').bind('click',function(){
		var row = $('#role_table').datagrid('getSelected');
		if(row){
			if(row.roleId==1||row.roleId==2){
				layer.msg('禁止修改最高权限');
			}else{
			$("#menudlg").dialog('open').dialog('setTitle','分配菜单');
			$("#menusaveUrl").val(row.roleId);
			openMenu(row.roleId);
			}
		}else{
			layer.msg('请选择身份');
		}
	});
})

/**
* easyui全选/反选
* @param Object obj 控件对象
*/
function treeChecked(obj) {
	var nodes = $('#menu').tree('getChildren');
	var flag = obj.checked ? "check" : "uncheck";
	for (var i = 0; i < nodes.length; i++) {
		$('#menu').tree(flag, nodes[i].target);// 将得到的节点选中
	}
} 

function roleSave(){
	pageSize = $('#role_table').datagrid('getPager').data(
	"pagination").options.pageSize;
	pageNumber =  $('#role_table').datagrid('getPager').data(
	"pagination").options.pageNumber;
	var datas={
			currentPage : (pageNumber - 1) * pageSize,
			pageSize:pageSize
			};
	$.ajax({
		url : $("#saveUrl").val(),
		type : "POST",
		dataType : "json",
		data : {
			roleName:$("#roleName").textbox('getValue'),
			roleDescription:$("#roleDescription").textbox('getValue')
		},
		beforeSend: function(){
			var flag=$("#rolefm").form('enableValidation').form('validate');
			if(flag){
				$('#save').linkbutton({disabled:true}); 
				return flag;
			}else{
	          return flag;
			}
         },
		success : function(result) {
			$('#save').linkbutton({disabled:false}); 
			if (result.result == 0) {
				layer.msg(result.tips);
			} else {
				layer.msg(result.tips);
				$('#roledlg').dialog('close'); // close the dialog
				$('#role_table').datagrid('reload',datas); // reload the data
			}
		}
	});
}	   

function roleCancel(){
	$('#save').linkbutton({disabled:false}); 
	$('#rolefm').form('clear');
	$('#roledlg').dialog('close');
}	
//菜单树	   
function openMenu(roleId){
	$('#menu').tree({
        	url: 'admin/queryMenuDetailsInfo.do?roleId='+roleId,
        	animate:true,
        	checkbox:true,
        	lines:true,
        	loadFilter: function(data){
        		return convert(data);
        	}
        });
       }
        function convert(data){
        	if(!data)
        	{
        		return null;
        	}
        	var arr1=[],arr2=[],arr3=[];
        	for(var n=0; n<data.rows.length; n++)
    		{
        		var row = data.rows[n];
        		if(row.menuLevel == 1)
    			{
        			arr1.push(row);
    			}
        		if(row.menuLevel == 2)
    			{
        			arr2.push(row);
    			}
        		if(row.menuLevel == 3)
    			{
        			arr3.push(row);
    			}
    		}
        	//三级插入了二级
        	for(var i=0;i<arr2.length;i++)
    		{
        		//这个二级下面的子类是否都是选中，前提是有children
        		arr2[i].isChildrenALLCheck = true;
        		for(var j=0;j<arr3.length;)
    			{
        			if(arr3[j].parentId == arr2[i].menuId)
    				{
        				var node3 = {
            					"id":arr3[j].menuId,
            					"text":arr3[j].menuName,
            					'menuLevel':arr3[j].menuLevel,
            			};
        				if(arr3[j].onSelect && arr3[j].onSelect==arr3[j].menuId)
    					{
        					node3.checked = true;
    					}
        				else
    					{
        					arr2[i].isChildrenALLCheck = false;
    					}
        				if(!arr2[i].children)
        				{
        					arr2[i].children = [];
        				}
        				arr2[i].children.push(node3);
        				arr3.splice(j, 1);
        				
    				}
        			else
    				{
        				j++;
    				}
    			}
    		}
        	var nodes = [];
        	for(var m = 0;m<arr1.length;m++)
    		{
        		var node = {
        				"id":arr1[m].menuId,
    					"text":arr1[m].menuName,
    					'menuLevel':arr1[m].menuLevel,
    					'state':'closed'
    					
        		};
        		var check = true;
        		for(var k = 0;k<arr2.length;)
    			{
        			if(arr2[k].parentId == arr1[m].menuId)
    				{
        				var node2 = {
            					"id":arr2[k].menuId,
            					"text":arr2[k].menuName,
            					'menuLevel':arr2[k].menuLevel
            			};
        				if(!arr2[k].children)
    					{
        					if(arr2[k].onSelect && arr2[k].onSelect==arr2[k].menuId)
    						{
        						node2.checked = true;
    						}
    					}
        				else
    					{
        					node2.children = arr2[k].children;
        					
        					if(arr2[k].isChildrenALLCheck)
    						{
        						node2.checked = true;
    						}
    					}
        				
        				if(!node.children)
        				{
        					node.children = [];
        				}
        				node.children.push(node2);
        				arr2.splice(k, 1);
        				if(!node2.checked)
    					{
        					check = false;
    					}
    				}
        			else
    				{
        				k++;
    				}
    			}
        		
        		if(check)
    			{
        			node.checked = true;
    			}
        		nodes.push(node);
    		}
        	
        	return nodes;
        }
        //判断是否存在
        function ishave(a,id)
        {
        	var result = false;
        	if(!!a && a.length>0)
    		{
        		for(var i = 0;i<a.length;i++)
    			{
        			if(a[i].id == id)
        				{
        				result = true;
        				break;
        				}
    			}
    		}
        	return result;
        }
		//menu保存按钮
		function saveMenuBtn() {
			var nodes = $('#menu').tree('getChecked',
					[ 'checked', 'indeterminate' ]);
			var roleId=$("#menusaveUrl").val();
			var menu='';
			var a = [];
			
			for (var i = 0; i < nodes.length; i++) 
			{
				if(nodes[i].menuLevel==1){
					var ishaveChild = false;
					
					
					var child = nodes[i].children;
					
					
					for(var j = 0;j<child.length;j++)
					{
						if(!ishave(a,child[j].id))
						{
							var n = child[j].children;
							if(!!n)
							{
								//
								var str = "";
								var ishave3 = false;
								for(var k = 0;k<n.length;k++)
								{
									if(n[k].checked==true)
									{
										ishave3 = true;
										if(k==n.length-1)
										{
											str+=n[k].id;
										}
										else
										{
											str+=n[k].id+",";
										}
									}
									
									
								}
								if(ishave3)
								{
									ishaveChild = true;
									a.push({"id":child[j].id,"ch":str});
								}
								
							}
							else
							{
								if(child[j].checked)
								{
									ishaveChild = true;
									a.push({"id":child[j].id,"ch":''});
								}
								
							}
						}
					}
					
					if(!ishave(a,nodes[i].id) && ishaveChild)
					{
						a.push({"id":nodes[i].id,"ch":''});
					}
					
				}
			}
			
			var data = JSON.stringify(a); 
			 if(a.length!=0){
				 $.ajax({
						url : 'admin/insertRoleMenuInfoBybatch.do',
						type : "POST",
						dataType : "json",
						data : {
							'menuId':data,
							'roleId':roleId
						},
						success : function(result) {
							if (result.result == 0) {
								layer.msg(result.tips);
							} else {
								layer.msg(result.tips);
								$('#menudlg').dialog('close'); // close the dialog
								$('#role_table').datagrid('reload'); // reload the data
							}
						}
				}); 
			 }else{
				 layer.msg('分配权限至少选择一个权限,否则取消分配');
			 }
		}
		//menu取消按钮
		function cancelMenuBtn(){
			$('#menudlg').dialog('close'); 
		}
		//loaddata
		var loadData = function(datas){
			 $.ajax({
	  				url : 'admin/queryRoleInfo.do',
	  				type : "POST",
	  				dataType : "json",						
	  				data : datas,
	  				success : function(param) {
	  						$('#role_table').datagrid('loadData',param);
	  				}
	  		});   
		}